import datetime
import json
from django.views.decorators.csrf import csrf_exempt
from deps.voidsdk.django.responses import api_success_response, api_error_response
from deps.voidsdk.django.validator import (validate_params, not_blank,
                                           bool_validator, normal_date, phone_number)

from .models import News, Comments, UserRelation, UserRelationStatus
from apps.user.models import Photos, ImageOrVideo
from apps.user.decorators import api_auth_required
from apps.user.service import get_api_access_token, get_user_info
from deps.voidsdk.django.modelautocode.tools import paginate_queryset



@csrf_exempt
@api_auth_required
@validate_params("GET", [
    {"name": "last_id", "clean_func": int, "required": True},
])
def new_list(request, cleaned_params):
    results = []
    new_obj = News.objects.all().order_by('-created')
    # 分页
    pagination_obj, pagination_data = paginate_queryset(new_obj, page_no=cleaned_params["last_id"], cnt_per_page=10,
                                                        half_show_length=5)
    if cleaned_params["last_id"] > pagination_data["page_cnt"]:
        pagination_obj = []

    for new in pagination_obj:
        result = {}
        result["user"] = get_user_info(new.user)
        result["user"]["is_attention"] = False
        result["is_up"] = False

        # 找出拉黑的用户关系
        user_relation = UserRelation.objects.filter(
            user=request.user, object_user=new.user, relation=UserRelationStatus.ATTENTION)

        if user_relation.count() > 0:
            continue
        # 找出关注的
        if UserRelation.objects.filter(user=request.user, object_user=new.user, relation=UserRelationStatus.BLACK).count() > 0:
            result["user"]["is_attention"] = True

        if new.up.filter(id=request.user.id).count() > 0:
            result["is_up"] = True

        # 得到每列的值
        for field in ("id", "content",
                      "position", "longitude", "latitude"):
            result[field] = getattr(new, field) if getattr(new, field) else ""

        if new.image:
            result["image"] = json.loads(new.image)
        if new.video:
            result["video"] = json.loads(new.video)
        else:
            result["video"] = []
        result["created"] = new.created.strftime("%Y-%m-%d %H:%M:%S") if new.created else None
        result["up"] = new.up.all().count()
        result["comment"] = new.comment_new.count()
        results.append(result)
    return api_success_response({"news": results})


@csrf_exempt
@api_auth_required
@validate_params("GET", [
    {"name": "new_id", "clean_func": int, "required": True},
])
def new_detail(request, cleaned_params):
    """
    动态详情
    :param request:
    :param cleaned_params:
    :return:
    """
    new = News.objects.get(id=cleaned_params["new_id"])  # 获取动态id
    result = {}
    # 将内容写入字典准备返回
    for field in ("id", "content", "position", "longitude", "latitude"):
        result[field] = getattr(new, field) if getattr(new, field) else ""
    if new.image:
        photo_obj = Photos.objects.get(id=new.image, type=ImageOrVideo.IMAGE)
        result["image"] = getattr(photo_obj, "url") if getattr(photo_obj, "url") else []
    else:
        result["image"] = []

    if new.video:
        photo_obj = Photos.objects.get(id=new.video, type=ImageOrVideo.VIDEO)
        result["video"] = getattr(photo_obj, "url") if getattr(photo_obj, "url") else []
    else:
        result["video"] = []
    result["created"] = new.created.strftime("%Y-%m-%d %H:%M:%S") if new.created else None
    result["up"] = new.up.all().count()  # 点赞数

    result["user"] = get_user_info(new.user)
    result["is_up"] = False  # 是否点赞
    result["user"]["is_attention"] = False  # 是否关注判断
    # 关注用户
    if UserRelation.objects.filter(user=request.user, object_user=new.user, relation=UserRelationStatus.ATTENTION).count() > 0:
        result["user"]["is_attention"] = True
    if new.up.filter(id=request.user.id).count() > 0:
        result["is_up"] = True

    result["comment"] = new.comment_new.count()  # 评论

    comments = []
    comments_obj = new.comment_new.filter(new=new).order_by('-created')
    for comment in comments_obj:
        if request.user:
            user_relation = UserRelation.objects.filter(
                user=request.user, object_user=new.user, relation=UserRelationStatus.Black)  # 拉黑用户
            if user_relation.count() > 0:
                continue
        obj_dict = {}
        obj_dict["id"] = comment.id
        obj_dict["content"] = comment.content
        obj_dict["created"] = comment.created.strftime("%Y-%m-%d %H:%M:%S") if comment.created else None
        obj_dict["user"] = get_user_info(comment.user)
        comments.append(obj_dict)
    return api_success_response({"new": result, "comments": comments})


@csrf_exempt
@api_auth_required
@validate_params("POST", [
    {"name": "content", "clean_func": json.loads, "required": True},
    {"name": "image", "clean_func": json.loads, "required": False},
    {"name": "video", "clean_func": json.loads, "required": False},
    {"name": "position", "clean_func": json.loads, "required": False},
    {"name": "longitude", "clean_func": json.loads, "required": False},
    {"name": "latitude", "clean_func": json.loads, "required": False},
])
def issue_new(request, cleaned_params):
    """
    发布动态
    """
    new = News(content=cleaned_params["content"])
    new.user = request.user
    for field in ("position", "longitude", "latitude"):
        if cleaned_params[field]:
            setattr(new, field, cleaned_params[field])

    # 检查是否有图像和视频,并保存至图片表
    if not cleaned_params['image']:
        new.image = []
    else:
        photos = Photos()
        photos.user = request.user
        setattr(new, "url", cleaned_params["image"])
        photos.type = ImageOrVideo.IMAGE
        photos.save()
        new.image = photos.id

    if not cleaned_params['video']:
        new.video = []
    else:
        photos = Photos()
        photos.user = request.user
        setattr(new, "url", cleaned_params["video"])
        photos.type = ImageOrVideo.VIDEO
        photos.save()
        new.video = photos.id
    new.save()

    return api_success_response({})


@csrf_exempt
@api_auth_required
@validate_params("POST", [
    {"name": "new_id", "clean_func": int, "required": True},
])
def delete_new(request, cleaned_params):
    """
    删除动态
    """
    new = News.objects.filter(id=cleaned_params["new_id"])
    if new[0].user != request.user:
        return api_error_response('您不能删除这条动态!')
    if new.count() > 0:
        new.delete()
        return api_success_response({})
    else:
        return api_error_response('动态不存在!')


@csrf_exempt
@api_auth_required
@validate_params("POST", [
    {"name": "content", "clean_func": json.loads, "required": True},
    {"name": "new_id", "clean_func": int, "required": True},
])
def issue_comment(request, cleaned_params):
    """
    发表评论
    """
    comment = Comments(content=cleaned_params["content"],
                       new_id=cleaned_params["new_id"])
    comment.user = request.user
    comment.save()
    return api_success_response({})


@csrf_exempt
@api_auth_required
@validate_params("POST", [
    {"name": "comment_id", "clean_func": int, "required": True},
])
def delete_comment(request, cleaned_params):
    """
    删除评论
    """
    comment = Comments.objects.filter(id=cleaned_params["comment_id"])
    if comment[0].user != request.user:
        return api_error_response('您不能删除这条评论!')
    if comment.count() > 0:
        comment.delete()
        return api_success_response({})
    else:
        return api_error_response('评论不存在!')


@csrf_exempt
@api_auth_required
@validate_params("POST", [
    {"name": "new_id", "clean_func": int, "required": True},
])
def up_new(request, cleaned_params):
    """
    点赞
    """
    try:
        new = News.objects.get(id=cleaned_params["new_id"])
    except News.DoesNotExist:
        return api_error_response('此动态不存在')
    new.up.add(request.user)
    return api_success_response({})


@csrf_exempt
@api_auth_required
@validate_params("POST", [
    {"name": "new_id", "clean_func": int, "required": True},
])
def cancel_up_new(request, cleaned_params):
    """
    取消点赞
    """
    try:
        new = News.objects.get(id=cleaned_params["new_id"])
    except News.DoesNotExist:
        return api_error_response('此动态不存在')
    new.up.remove(request.user)
    return api_success_response({})


@csrf_exempt
@api_auth_required
@validate_params("POST", [
    {"name": "user_id", "clean_func": int, "required": True},
])
def attention(request, cleaned_params):
    """
    关注
    """
    user_relation = UserRelation.objects.filter(user=request.user, object_user__id=cleaned_params["user_id"])
    if user_relation.count() == 0:
        create_relation = UserRelation()
        create_relation.user = request.user
        create_relation.object_user_id = cleaned_params["user_id"]
        create_relation.relation = UserRelationStatus.attention
        create_relation.save()
    else:
        user_relation.update(relation=UserRelationStatus.attention)
    return api_success_response({})


@csrf_exempt
@api_auth_required
@validate_params("POST", [
    {"name": "user_id", "clean_func": int, "required": True},
])
def cancel_attention(request, cleaned_params):
    """
    取消关注
    """
    user_relation = UserRelation.objects.filter(user=request.user,
                                                object_user__id=cleaned_params["user_id"],
                                                relation=UserRelationStatus.attention).delete()
    return api_success_response({})


@csrf_exempt
@api_auth_required
@validate_params("POST", [
    {"name": "user_id", "clean_func": int, "required": True},
])
def join_black(request, cleaned_params):
    """
    拉黑
    """
    user_relation = UserRelation.objects.filter(user=request.user, object_user__id=cleaned_params["user_id"])
    if user_relation.count() == 0:
        create_relation = UserRelation()
        create_relation.user = request.user
        create_relation.object_user_id = cleaned_params["user_id"]
        create_relation.relation = UserRelationStatus.black.value
        create_relation.save()
    else:
        user_relation.update(relation=UserRelationStatus.black)
    return api_success_response({})


@csrf_exempt
@api_auth_required
@validate_params("POST", [
    {"name": "user_id", "clean_func": int, "required": True},
])
def cancle_join_black(request, cleaned_params):
    """
    取消拉黑
    """
    user_relation = UserRelation.objects.filter(user=request.user,
                                                object_user__id=cleaned_params["user_id"],
                                                relation=UserRelationStatus.black).delete()
    return api_success_response({})
